package com.ruoyi.web.controller.app;

import com.ruoyi.business.domain.TOrder;
import com.ruoyi.business.domain.TOrderItem;
import com.ruoyi.business.service.ITOrderService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.page.TableDataInfo; // 引入分页结果类
import com.ruoyi.business.domain.TOrder; // 引入TOrder

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * App端 订单接口
 *
 * @author your_name
 */
@RestController
@RequestMapping("/app/order")
public class AppOrderController extends BaseController {

    @Autowired
    private ITOrderService orderService;

    /**
     * 预下单/订单确认
     */
    @PostMapping("/preview")
    public AjaxResult preview(@RequestBody Map<String, Object> params) {
        try {
            // 调用Service层的方法来处理业务逻辑
            Map<String, Object> previewResult = orderService.previewOrder(params);
            return AjaxResult.success(previewResult);
        } catch (ServiceException e) {
            // 捕获业务异常，返回友好的错误信息
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            // 捕获其他未知异常
            logger.error("预下单异常", e);
            return AjaxResult.error("计算订单信息失败，请稍后再试");
        }
    }

    /**
     * 创建订单
     */
    @PostMapping("/create")
    public AjaxResult create(@RequestBody Map<String, Object> params) {
        try {
            // 调用Service层的方法来处理创建订单的业务逻辑
            TOrder createdOrder = orderService.createOrder(params);

            // 只返回最关键的信息给前端
            Map<String, Object> result = new HashMap<>();
            result.put("orderId", createdOrder.getOrderId());
            result.put("orderSn", createdOrder.getOrderSn());

            return AjaxResult.success("订单创建成功，请尽快支付", result);
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("创建订单异常", e);
            return AjaxResult.error("创建订单失败，请稍后再试");
        }
    }

    /**
     * 模拟支付成功
     * @param params 包含 "orderId"
     * @return
     */
    @PostMapping("/mock-pay")
    public AjaxResult mockPay(@RequestBody Map<String, Object> params) {
        try {
            Long orderId = Long.valueOf(params.get("orderId").toString());
            // 调用Service层处理支付成功的逻辑
            boolean result = orderService.processPaySuccess(orderId);
            return result ? AjaxResult.success("模拟支付成功") : AjaxResult.error("支付处理失败");
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("模拟支付异常", e);
            return AjaxResult.error("模拟支付失败，请稍后再试");
        }
    }

    /**
     * 3.4 获取我的订单列表 (分页)
     */
    @GetMapping("/list")
    public TableDataInfo list(TOrder order) {
        // 设置当前用户ID，防止查询到别人的订单
        order.setUserId(SecurityUtils.getUserId());

        // 开启分页
        startPage();

        // 调用Service进行查询
        List<TOrder> list = orderService.selectOrderListWithItems(order);

        // 封装成分页结果返回
        return getDataTable(list);
    }

    /**
     * 3.5 获取订单详情
     */
    @GetMapping("/detail/{orderId}")
    public AjaxResult getDetail(@PathVariable("orderId") Long orderId) {
        TOrder order = orderService.selectOrderDetailById(orderId);

        // 安全校验：确保用户只能查看自己的订单
        if (order == null || !order.getUserId().equals(SecurityUtils.getUserId())) {
            return AjaxResult.error("订单不存在或无权访问");
        }

        return AjaxResult.success(order);
    }
}